<template>
  <div class="pushbigbox">
     <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
          <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item label="推送企业">
                  <FilterSelect 
                      ref="yonghu" 
                      :optionlist="userinfolist" 
                      :valuekey="{name:'name',value:'id'}"
                      :defaultvalue="danwei"
                      @changeselect="changeqite"
                      ></FilterSelect>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="是否启用">
                  <el-switch v-model="value1"></el-switch>
                </el-form-item>
              </el-col>
              <el-col :span="14" style="text-align: right;">
                <el-form-item label="">
                  <el-button type="primary" size="small" @click="getlist">查 询</el-button>
                </el-form-item>
              </el-col>
          </el-row>
      </el-form>
     </div>
     <div class="bodybox">
      <div class="title">
        <div>推送服务配置</div>
        <div class="butti">
          <span><el-button style="margin-right: 10px;" type="primary" size="small" @click="addmodel"><i class="el-icon-plus"></i>新增配置</el-button></span>
          <TopTile @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile>
        </div>
      </div>
      <div class="table">
        <TableColumn
        ref="tabledata"
        :tableData="tableData" 
        :tableConfig="tableConfig" 
        :issize="issize">
        <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center">
        </el-table-column>
        <el-table-column
            label="推送单位">
            <template #default="{row}">
               <span>{{ userinfolist.filter(ele=>ele.id==row.manageNo)[0]?.name }}</span>
            </template>
        </el-table-column>
        <el-table-column
          prop="pushUrl"
          label="推送地址">
        </el-table-column>
        <el-table-column
          prop="pushType"
            label="推送内容">
            <template #default="{row}">
               <span>{{ row.pushType=='1'?'数据':row.pushType=='2'?'事件':'数据+事件' }}</span>
            </template>
        </el-table-column>
        <el-table-column
          prop="secToken"
            label="签名令牌">
        </el-table-column>
        <el-table-column
            label="加密传输"
            align="center">
            <template #default="{row}">
              <span v-if="row.isEncrypted=='0'" class="states red"></span>
              <span v-else class="states green"></span>
              <span>{{ row.isEncrypted=='0'?'未加密':'已加密' }}</span>
            </template>
        </el-table-column>
        <el-table-column
          prop="pushInterval"
            label="推送间隔(s)"
            align="center">
        </el-table-column>
        <el-table-column
            label="启用状态"
            align="center">
            <template #default="{row}">
              <span v-if="row.isEnabled=='0'" class="states red"></span>
              <span v-else class="states green"></span>
              <span>{{ row.isEnabled=='0'?'未启用':'启用' }}</span>
            </template>
        </el-table-column>
        <el-table-column
            prop="address"
            label="操作"
            width="160">
            <template #default="{row}">
              <el-tooltip class="item" effect="dark" content="启用" placement="top" v-if="row.isEnabled=='0'">
                <i @click="openorstop(row)"  class="iconfont icon-qiyong" style="color:#b8e412 ;margin-right: 15px; cursor: pointer;font-size: 17px;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="停用" placement="top" v-else>
                <i @click="openorstop(row)" class="iconfont icon-tingyong" style="color:#f2bd42;margin-right: 15px; cursor: pointer;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <i @click="update(row)" class="el-icon-edit" style="color:#1a90fe ;margin-right: 15px; cursor: pointer;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i @click="deletes(row)" class="el-icon-delete" style="color: red;cursor: pointer;margin-right: 15px;"></i>
              </el-tooltip>
            </template>
        </el-table-column>
      </TableColumn>
         <!-- 底部分页 -->
         <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pages.pageNo"
                :page-size="20"
                @current-change="getlist"
                :total="+totalCount">
          </el-pagination>
          </div>
      </div>
      <div>
        <el-dialog
          title="推送服务配置信息"
          :visible.sync="dialogVisible"
          width="40%">
          <div>
            <el-form ref="form" :model="form" label-width="80px">
               <el-row>
                 <el-col :span="24">
                   <el-form-item label="推送单位" prop="manageNo">
                    <el-select v-model="form.manageNo" placeholder="请选择推送单位" style="width: 80%;" size="small">
                      <el-option v-for="item in userinfolist" :key="item.value" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                   </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                 <el-col :span="24">
                   <el-form-item label="推送地址" prop="pushUrl">
                    <el-input v-model="form.pushUrl" placeholder="请选择推送地址" style="width: 80%;" size="small"></el-input>
                   </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                 <el-col :span="24">
                   <el-form-item label="推送令牌" prop="secToken">
                    <el-input v-model="form.secToken" placeholder="请输入推送令牌" style="width: 80%;margin-right: 10px;" size="small"></el-input>
                    <el-button type="primary" @click="shengchenglinpai" size="small">随机生成</el-button>
                   </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                 <el-col :span="24">
                   <el-form-item label="加密传输" prop="isEncrypted">
                    <el-radio-group v-model="form.isEncrypted">
                      <el-radio :label="0">不加密</el-radio>
                      <el-radio :label="1">加密</el-radio>
                    </el-radio-group>
                   </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                 <el-col :span="24">
                   <el-form-item label="加密密钥" prop="aesKey">
                    <el-input v-model="form.aesKey" placeholder="请输入加密密钥" style="width: 80%;margin-right: 10px;" size="small"></el-input>
                    <el-button type="primary" @click="shengchengmiyao" size="small">随机生成</el-button>
                   </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                 <el-col :span="24">
                   <el-form-item label="推送内容" prop="pushType">
                    <el-radio-group v-model="form.pushType">
                      <el-radio label="1">数据</el-radio>
                      <el-radio label="2">事件</el-radio>
                      <el-radio label="3">数据+事件</el-radio>
                    </el-radio-group>
                   </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                 <el-col :span="24">
                   <el-form-item label="推送间隔">
                    <el-input v-model="form.pushInterval" placeholder="请选择推送间隔" style="width: 80%;" size="small">
                     <span slot="suffix">秒</span>
                    </el-input>
                   </el-form-item>
                  </el-col>
                </el-row>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="diaquxiao" size="small">取 消</el-button>
            <el-button type="primary" @click="submit" size="small">确 定</el-button>
          </span>
        </el-dialog>
      </div>
     </div>
  </div>
</template>

<script>
import FilterSelect from '@/components/FilterSelect'
import TopTile from '@/components/TopTitle/index.vue'
import TableColumn from '@/components/Table/index.vue'
import { exportexcel } from '@/utils/excel'
import { getCompanyInfo } from '@/api/layout'
import {gettablelistapi,postaddpeizhiapi,postupdatepeizhiapi,postdelpeizhiapi,poststoporopenapi,postjihuoapi} from '@/api/energy-consumption/Basic-information/pushservice'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTile,
    TableColumn,
    FilterSelect
},
  data() {
    return {
      form:{},
      danwei: '',
      value1:false,
      dialogVisible:false,
      issize: 'medium',
      tableData: [],
      tableConfig: [],
      pages: {
        pageNo: 1,
        pageSize:20
      },
      totalCount: '',
      userinfolist: [],
      flag:false
    };
  },

  async mounted() {
    const { data: { list } } = await getCompanyInfo()
    this.userinfolist = this.flatten(list)
    this.danwei = this.userinfolist[0].id
    this.getlist() 
  },

  methods: {
    changeqite(val) {
      this.$set(this,'danwei',val)
    },
    // 弹窗确定
    async submit() {
      this.flag ? await postupdatepeizhiapi(this.form).then(res => {
        this.$message({
          type: res.code == '200' ? 'success' : 'warning',
          message:res.code == '200' ? '修改成功' :res.message
        })
      }):
      await postaddpeizhiapi(this.form).then(res => {
        this.$message({
          type: res.code == '200' ? 'success' : 'warning',
          message:res.code == '200' ? '新增成功' :res.message,
        })
      })
      this.diaquxiao()
      this.getlist() 
    },
    // 启用/停用
    openorstop(row) {
      this.$confirm(`此操作将${row.isEnabled=='0'?'启用':'停用'}该项配置, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            await poststoporopenapi({ isEnabled: row.isEnabled=='0'?'1':'0', id: row.id })
            await postjihuoapi({ pushId: row.id })
            this.$message.success('操作成功')
          } catch (error) {
            this.$message.warning(`${error}`)
          }
          this.getlist() 
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 删除
    deletes(row) {
      this.$confirm('此操作将永久删除该档案, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
           try {
            await postdelpeizhiapi({ id: row.id })
            await postjihuoapi({ pushId: row.id })
            this.$message.success('删除成功')
           } catch (error) {
            this.$message.warning(`${error}`)
           }
            this.getlist() 
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 修改
    update(row) {
      this.dialogVisible = true
      const {isEnabled,...obj}=row
      this.form = { ...obj }
      this.flag=true
    },
    // 新增
    addmodel() {
      this.dialogVisible = true
      this.flag = false
      this.$set(this.form,'manageNo',this.danwei)
    },
    // 弹窗取消
    diaquxiao() {
      this.dialogVisible = false
      this.$refs.form.resetFields()
    },
    // 处理树结构
    flatten(arr) {
        return arr.reduce((acc, cur) => {
            if (cur.children) {
                acc.push(cur);
                acc = acc.concat(this.flatten(cur.children));
            } else {
                acc.push(cur);
            }
            return acc;
        }, []);
    },
    // 生成随机令牌
    shengchenglinpai() {
      this.$set(this.form,'secToken',this.generateRandomString(32))
    },
    // 生成随机密钥
    shengchengmiyao() {
      this.$set(this.form,'aesKey',this.generateRandomString(42))
    },
    // 获取表格数据
    async getlist() {
      this.$refs.tabledata.loading=true
      const { data: { list, totalCount } } = await gettablelistapi({
        pageNo: this.pages.pageNo-1,pageSize: this.pages.pageSize,
        isEnabled:this.value1?'1':'0',manageNo:this.danwei
      })
      this.tableData = list
      this.totalCount = totalCount
      this.$refs.tabledata.loading=false
    },
   // 调节表格密度
  command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      exportexcel(
        'sst-microservice-biz/dt/push/global/conf/export',
        { isEncrypted:this.value1?'1':'0',manageNo:this.danwei },
        '推送服务配置'
      )
    },
    // 刷新列表
    shuaxin() {
      this.getlist()
      this.$message.success('列表刷新成功')
    },
    generateRandomString(number) {
      let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let result = '';
      for (let i = 0; i < number; i++) {
          result += characters.charAt(Math.floor(Math.random() * characters.length));
      }
      return result;
    }
  },
};
</script>

<style scoped>

.pushbigbox{
  height: 100%;
  padding: 10px;
  .topbox{
    height: 80px;
    padding: 20px;
    background-color: #fff;
    margin-bottom: 10px;
  }
  .bodybox{
    height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .title{
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .butti{
        display: flex;
      }
    }
    .table{
      height: 90%;
      .states{
        display: inline-block;
        width: 10px;
        height: 10px;
        margin-right: 10px;
        border-radius: 50%;
      }
      .red{
        background-color:red;
      }
      .green{
        background-color: #13ce66;
      }
      .fenye{
        text-align: right;
        margin-top: 10px;
      }
    }
  }
}
::v-deep .el-dialog__footer{
  text-align: center;
}
</style>